package arithmetic1.list;

public class BothwayLinkedList {
    //头结点
    private BothwayNode head;

    private BothwayLinkedList(BothwayNode head){
        this.head=head;
    }

    //在尾部添加一个节点
    public void add(BothwayNode node){
        BothwayNode temp=head.next;
        if(temp==null){ //链表为空
            head.next=node;
            node.pre=head;
        }else {
            while (temp.next!=null){
                temp=temp.next;
            }
            temp.next=node;
            node.pre=temp;
        }
    }

    //删除data域为某个值的第一个节点
    public void remove(int num){
        BothwayNode temp=head.next;
        if(temp==null){
            System.out.println("链表为空,删除失败");
        }else {
            while (temp!=null && num!=temp.data){
               temp=temp.next;
            }
            temp.pre.next=temp.next;
            if(temp.next!=null){    //要删除的节点不是最后一个
                temp.next.pre=temp.pre;
            }
            temp.pre=null;
            temp.next=null;
        }
    }

    //打印双向链表
    public void print(){
        BothwayNode temp=head.next;
        if(temp==null){
            System.out.println("链表为空");
            return;
        }
        while (temp!=null) {
            System.out.print(temp+"\t");
            temp=temp.next;
        }
        System.out.println();
    }

    public static void main(String[] args) {
        BothwayNode head=new BothwayNode();
        BothwayLinkedList linkedList=new BothwayLinkedList(head);
        linkedList.add(new BothwayNode(2));
        linkedList.add(new BothwayNode(4));
        linkedList.add(new BothwayNode(1));
        linkedList.add(new BothwayNode(3));
        linkedList.add(new BothwayNode(8));
        System.out.println("删除前:");
        linkedList.print();
        linkedList.remove(2);
        System.out.println("删除后:");
        linkedList.print();
    }

}

class BothwayNode{
    int data;
    BothwayNode pre;
    BothwayNode next;

    public BothwayNode() {
    }

    public BothwayNode(int data) {
        this.data = data;
        this.pre=null;
        this.next=null;
    }

    @Override
    public String toString() {
        return data+"";
    }
}
